/**
 * Created by seikann on 2017-11-24.
 */
const models = require('../mongoDB/db');
const express = require('express');
const router = express.Router();


//新增个人信息
router.post("/api/personInfo/addInfo", (req, res) => {
  if (req.session.user) {
// 通过模型去查找数据库
    let newInfo = new models.perInfo({
      userName: req.body.userName,
      userType: req.body.userType,
      nickName: req.body.nickName,
      phone: req.body.phone,
      email: req.body.email,
      intro: req.body.intro
    });
    newInfo.save((err, data) => {
      if (err) {
        res.send(err);
      } else {
        res.send({
          message: "保存成功",
          code: "0"
        });
      }
    });
  } else {
    res.send({
      message: "请登录",
      code: "1"
    });

  }
});

//获取个人信息
router.get("/api/personInfo/getInfo", (req, res) => {
  if (req.session.user) {
// 通过模型去查找数据库
    let criteria = {userName: req.query.userName};
    models.perInfo.findOne(criteria, (err, data) => {
      if (err) {
        res.send(err);
      } else {
        let dataNew = {
          code:"0",
          message:"查询成功",
          data:""
        };
        dataNew.data = data;
        res.send(dataNew);
      }
    });
  } else {
    res.send({
      message: "请登录",
      code: "1"
    });

  }
});
//更新个人信息
router.post("/api/personInfo/updateInfo", (req, res) => {
  if (req.session.user) {
// 通过模型去查找数据库
    let criteria = {userName: req.body.userName};
    let updates = {
      $set: {
        userType: req.body.userType,
        nickName: req.body.nickName,
        phone: req.body.phone,
        email: req.body.email,
        intro: req.body.intro
      }
    };
    let options = {upsert: true};
    if (Boolean(criteria.userName)) {
      models.perInfo.update(criteria, updates, options, (err, data) => {
        if (err) {
          res.send(err);
        } else {
          res.send({
            message: "保存成功",
            code: "0"
          });
        }
      });
    } else {
      res.send({
        message: "目标账号不存在",
        code: "-1"
      });
    }
  } else {
    res.send({
      message: "请登录",
      code: "1"
    });
  }
});
module.exports = router;
